﻿#pragma once
#ifndef WRBUFFERS_H
#define WRBUFFERS_H

#include "WRArray.h"
#include "WRBuffer.h"
#include <QMutex>
#include <QAtomicInt>
#include <QMutexLocker>

//表示缓存集，提供对多个缓存的管理。
template <class T> class WRBuffers
{
public:
    typedef WRBuffer<T> Entry;

private:
    WRArray<Entry*> m_array;
    WRu m_count;
    QMutex m_mutex;
    QAtomicInt m_refCnt;

    //禁用复制构造函数和赋值操作符。
    Q_DISABLE_COPY(WRBuffers)

    //清理当前对象所占用的相关资源。
    inline ~WRBuffers(void)
    {
        for(WRu i = 0; i < m_count; ++i)
        {
            m_array[i]->release();
        }
    }

public:
    //初始化缓存集。
    inline explicit WRBuffers(WRu maxCount)
        : m_array(maxCount), m_refCnt(1)
    {
        m_count = maxCount;
        for(WRu i = 0; i < m_count; ++i)
        {
            m_array[i] = new Entry();
        }
    }
    //初始化缓存集。
    inline WRBuffers(WRu maxCount, WRu capacity)
        : m_array(maxCount), m_refCnt(1)
    {
        m_count = maxCount;
        for(WRu i = 0; i < m_count; ++i)
        {
            m_array[i] = new Entry(capacity);
        }
    }

    //添加对象引用。
    inline void addRef(void)
    {
        m_refCnt.ref();
    }
    //释放对象引用, 如果引用计数为0，则删除对象，返回True，否则返回False。
    inline bool release(void)
    {
        if (!m_refCnt.deref())
        {
            delete this;
            return true;
        }
        return false;
    }

    //请求缓存，如果成功，返回该缓存，否则返回NULL。
    Entry* request(void)
    {
        QMutexLocker lock(&m_mutex);
        if (m_count)
        {
            --m_count;
            return m_array[m_count];
        }
        return 0;
    }
    //释放缓存。
    void release(Entry* buffer)
    {
        QMutexLocker lock(&m_mutex);
        m_array[m_count] = buffer;
        ++m_count;
    }
};

#endif // WRBUFFERS_H

